<template>
  <div style="display: flex; height: 100%">
    <!-- 关系图 -->
    <div style="width: 70%; border: 1px solid #ece6e6">
      <div ref="chart" style="width: 100%; height: 100%"></div>
    </div>
    <!-- 列表 -->
    <div style="flex: 1; height: 100%; overflow-x: scroll">
      <el-card
        style="min-height: 250px"
       
      >
        <div slot="header">
          <b>用户关系列表</b>
        </div>
        <div class="user-info-card" v-for="(item, index) in userData" :key="index">
          <div class="info-item">
            <span class="label">用户ID：</span>
            <span class="value">{{ item.targetid }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户名称：</span>
            <span class="value">{{ item.targetName }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户城市：</span>
            <span class="value">{{ item.targetCity }}</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { detailsRelationship3 } from "@/api/combatUser/importantUser";

export default {
  name: "relationship",
  props: {
    ID: {
      type: String,
      default: "",
    },
    userInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      analyzeData: {},
      chartInstance: null,
      userData: [],
    };
  },
  mounted() {
    //页面展示loading
    // this.$loading({
    //   lock: true,
    //   text: "初始化图形请稍后",
    //   background: "rgba(0, 0, 0, 0.7)",
    // });
    detailsRelationship3(this.ID).then((res) => {
      if (res.code == 200) {
        this.userData = res.rows;
        this.handleDatanew(res.rows);
     
      } else {
        this.$message.error("获取用户数据失败！");
      }
    });
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    async handleDatanew(data) {
      // 创建Promise数组
      const promises = data.map((item) =>
        detailsRelationship3(item.targetid).then((res) => {
          if (res.code === 200) {
            item.childLst = res.rows; // 直接修改原对象
          }
          return item; // 返回修改后的item
        })
      );

      // 等待所有请求完成
      const processedData = await Promise.all(promises);

      // 这里可以安全使用最终结果
      console.log("最终结果:", processedData);
      const result = this.processData(this.ID, processedData); // 执行下一步操作
      console.log("resultresultresultresult", result);
      this.chartInstance = echarts.init(this.$refs.chart);
      let chartOptions = {
        backgroundColor: '#ffffff',
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ccc',
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: '#333'
          },
          formatter: params => {
            if (params.dataType === 'node') {
              return `
                <div style="text-align:center; padding: 5px;">
                  <img src="${params.data.avatar}" style="width:60px;height:60px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 10px rgba(0,0,0,0.1)"/><br/>
                  <div style="margin-top:8px;font-size:14px;font-weight:bold;color:#333">${params.data.name}</div>
                  <div style="margin-top:4px;font-size:12px;color:#666">${params.data.city || ''}</div>
                </div>
              `;
            }
            return `<div style="padding:5px;font-size:12px;color:#666">${params.data.name}关系</div>`;
          }
        },
        legend: {
          data: ['中心用户', '直接关系', '间接关系'],
          textStyle: {
            color: '#666',
            fontSize: 12
          },
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 20,
          padding: [10, 20]
        },
        series: [{
          type: 'graph',
          layout: 'force',
          force: {
            repulsion: 200,  // 减小节点之间的斥力
            edgeLength: 80,  // 减小边的长度
            gravity: 0.1,    // 增加向心力
            layoutAnimation: true
          },
          draggable: true,
          data: result.nodes,
          links: result.links,
          categories: [
            { name: '中心用户' },
            { name: '直接关系' },
            { name: '间接关系' }
          ],
          roam: true,
          zoom: 0.8,        // 设置默认缩放比例
          scaleLimit: {     // 设置缩放限制
            min: 0.4,
            max: 2
          },
          focusNodeAdjacency: true,
          label: {
            show: true,
            position: 'right',
            formatter: '{b}',
            fontSize: 12,
            color: '#333',
            backgroundColor: 'rgba(255, 255, 255, 0.7)',
            padding: [4, 8],
            borderRadius: 4
          },
          lineStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [{
                offset: 0,
                color: '#91cc75'
              }, {
                offset: 1,
                color: '#5470c6'
              }]
            },
            width: 1.5,
            curveness: 0.3,
            opacity: 0.6
          },
          itemStyle: {
            color: function(params) {
              const colorList = ['#5470c6', '#91cc75', '#fac858'];
              return colorList[params.data.category];
            },
            borderColor: '#fff',
            borderWidth: 2,
            shadowColor: 'rgba(0, 0, 0, 0.2)',
            shadowBlur: 10
          },
          emphasis: {
            lineStyle: {
              width: 3,
              opacity: 1
            },
            itemStyle: {
              shadowBlur: 20
            },
            label: {
              fontSize: 14,
              fontWeight: 'bold'
            }
          }
        }]
      };
      this.chartInstance.setOption(chartOptions);
      

    },
    processData(centerId, rawData) {
      const nodes = [];
      const links = [];

      // 1. 添加中心节点
      nodes.push({
        id: centerId,
        name: "中心用户",
        value: 100, // 节点大小
        category: 0, // 节点类型 (0=中心节点)
        symbolSize: 50, // 中心节点最大
        avatar: this.userInfo.avatar,
      });

      // 2. 处理第一层关系
      rawData.forEach((item) => {
        // 添加第一层节点
        nodes.push({
          id: item.targetid,
          name: item.targetName,
          city: item.targetCity,
          avatar: item.avatar,
          value: 60,
          category: 1, // 第一层关系节点
          symbolSize: 35,
        });

        // 添加中心节点到第一层节点的连线
        links.push({
          source: centerId,
          target: item.targetid,
          name: item.relation,
        });

        // 3. 处理第二层关系
        if (item.childLst && item.childLst.length) {
          item.childLst.forEach((child) => {
            // 添加第二层节点
            nodes.push({
              id: child.targetid,
              name: child.targetName,
              city: child.targetCity,
              avatar: child.avatar,
              value: 30,
              category: 2, // 第二层关系节点
              symbolSize: 20,
            });

            // 添加第一层到第二层的连线
            links.push({
              source: item.targetid,
              target: child.targetid,
              name: child.relation,
            });
          });
        }
      });

      // 4. 去重节点 (防止重复ID)
      const uniqueNodes = Array.from(new Set(nodes.map((n) => n.id))).map(
        (id) => nodes.find((n) => n.id === id)
      );

      return { nodes: uniqueNodes, links };
    },
   
  },
};
</script>

<style scoped>
.el-card {
  margin-bottom: 10px;
}

.user-info-card {
  display: flex;
  flex-direction: row;
  border: 1px solid #dcdfe6;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.user-info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.info-item {
  margin-right: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-item:last-child {
  margin-right: 0;
}

.label {
  color: #606266;
  font-size: 14px;
  margin-right: 8px;
}

.value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}
</style>
